# -*- coding: utf-8 -*-
import os
import Models
import MasterPage
import time
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from datetime import datetime

class MainPage(webapp.RequestHandler):
    
    def get(self):
        user = GetUser(self)
        if user:
            ReCalculateAverage(user,self)  
            DisplayDynamic(user,self,'')

    def post(self):
        user = GetUser(self)

        actionType = self.request.POST.get('actiontype')

        if (actionType == 'Save'):
            SaveData(user,self)
        elif (actionType == 'Clear'):
            ClearData(user)
        elif (actionType == 'Delete'):
            DeleteData(user,self)

        ReCalculateAverage(user,self)  
        DisplayDynamic(user,self,actionType)    
         
application = webapp.WSGIApplication([('/', MainPage)],debug=True)

    
def GetUser(self):
    user = users.get_current_user()
    if user:
        self.response.headers['Content-Type'] = 'text/html'
##        self.response.out.write('Hello, ' + user.nickname())
    else:
        self.redirect(users.create_login_url(self.request.uri))
    return user


def SaveData(user,self):
    date = self.request.POST.get('date')
    currentkilo = self.request.POST.get('currentkilo')
    percost = self.request.POST.get('percost')
    price = self.request.POST.get('price')

    gsModel = Models.GasticsModel(User = user)
    gsModel.Email = user.email()
    
    curitem = self.request.POST.get('curitem')
    if (curitem <> ''):
        gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author AND CurrentKilo = :currentkilo", author=user.email(), currentkilo=int(curitem))
        if gasticsModel.count() > 0:
            gsModel = gasticsModel[0]
    
    gsModel.Date = datetime.strptime(date, '%m-%d-%Y')
    gsModel.CurrentKilo = int(currentkilo)
    gsModel.PerCost = int(percost)
    gsModel.Price = float(price)
    
    gsModel.PerVolume = float(float(percost) / float(price))
    
    gsModel.put()

    SaveCarModel(user,self)

def SaveCarModel(user,self):
    carmodel = self.request.POST.get('carmodel')
    userCars = db.GqlQuery("SELECT * FROM UserCarModel WHERE Email = :author", author=user.email())
    if userCars.count() > 0:
        userCars[0].CarModel = carmodel
        userCars[0].put()
    else:
        newUserCar = Models.UserCarModel(User = user)
        newUserCar.CarModel = carmodel
        newUserCar.put()

def GetCarModel(user):
    userCars = db.GqlQuery("SELECT * FROM UserCarModel WHERE Email = :author", author=user.email())
    if userCars.count() > 0:
        return userCars[0].CarModel
    return 'Golf 1.4'

def DeleteData(user,self):
    curitem = self.request.POST.get('curitem')
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author AND CurrentKilo = :currentkilo", author=user.email(), currentkilo=int(curitem))
    if gasticsModel.count() > 0:
        gasticsModel[0].delete()

def ReCalculateAverage(user,self):
    sumVol = 0
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author", author=user.email())
    if (gasticsModel.count() > 0):
        startKilo = gasticsModel[0].CurrentKilo
    for gsModel in gasticsModel:
        kiloDrived = int(gsModel.CurrentKilo) - int(startKilo)
        if (kiloDrived == 0):
            gsModel.AverageGasCost = float(0)
        else:
            gsModel.AverageGasCost = float((float(sumVol) / kiloDrived) * 100)
        gsModel.put()
        sumVol += gsModel.PerVolume
    
def DisplayDynamic(user,self,actionType):
    dataGrid =  DrawTable(user)
    lastK = GetLastK(user)

    editDay = datetime.today().strftime('%m-%d-%Y')
    editK = ''

    operTitle = '输入数据'
    if (actionType <> 'Edit'):
        lastPrice = GetLastPrice(user)
        lastCost = GetLastCost(user)
        curitem = ''
    else:
        curitem = self.request.POST.get('curitem')
        gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author AND CurrentKilo = :currentkilo", author=user.email(), currentkilo=int(curitem))
        if gasticsModel.count() > 0:
            editDay = gasticsModel[0].Date.strftime('%m-%d-%Y')
            editK = gasticsModel[0].CurrentKilo
            lastPrice = gasticsModel[0].Price
            lastCost = gasticsModel[0].PerCost
        operTitle = '编辑数据'
    
    chartValues = GetChartValues(user)
    Y = GetGasCount(user)

    carModel = GetCarModel(user)

    header = MasterPage.OutputHeader(user)
    footer = MasterPage.OutputFooter()
    
    template_values = {'header': header, 'footer': footer, 'nickname': user.nickname(), 'dataGrid': dataGrid,\
                        'lastprice': lastPrice,\
                        'lastcost': lastCost,\
                        'lastk': lastK,\
                        'editDay': editDay,\
                        'editK': editK,\
                        'curitem': curitem,\
                        'chartvalues': chartValues,\
                        'opertitle': operTitle,\
                        'carselected': carModel,\
                        'y': Y}

    path = os.path.join(os.path.dirname(__file__), 'html/Default.html')
    self.response.out.write(template.render(path, template_values))

    
def DrawTable(user):
    dataGrid = ''
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author", author=user.email())
    for gsModel in gasticsModel:
        dataGrid += ('<tr><td>'
                     +  str(gsModel.Date.strftime('%m-%d-%Y'))
                     + '</td><td>' + str(gsModel.CurrentKilo)
                     + '</td><td>' + str(gsModel.PerCost)
                     + '</td><td>' + str('%.2f'%(gsModel.Price))
                     + '</td><td>' + str('%.2f'%(gsModel.PerVolume))
                     + '</td><td>' + str('%.2f'%(gsModel.AverageGasCost))
                     + '</td><td>' + '<a href="javascript:OnSubmitForm(\'Edit\',\''
                     + str(gsModel.CurrentKilo) + '\');"><img src="/images/edit.bmp" alt="Edit" border="0"></a> <a href="javascript:OnSubmitForm(\'Delete\',\''
                     + str(gsModel.CurrentKilo) + '\');"><img src="/images/delete.bmp" alt="Delete" border="0"></a>'
                     + '</td></tr>')
    
    return dataGrid

def ClearData(user):
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author", author=user.email())
    for gsModel in gasticsModel:
        gsModel.delete()

#display for input convenience
def GetLastPrice(user):
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author", author=user.email())
    if gasticsModel.count() > 0:
        return gasticsModel[gasticsModel.count()-1].Price
    else:
        return ''
    
#display for input convenience    
def GetLastCost(user):
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author", author=user.email())
    if gasticsModel.count() > 0:
        return gasticsModel[gasticsModel.count()-1].PerCost
    else:
        return ''
    
#for validation
def GetLastK(user):
    max = 0
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author", author=user.email())
    if gasticsModel.count() > 0:
        return gasticsModel[gasticsModel.count()-1].CurrentKilo
    else:
        return 0

def GetChartValues(user):
    chartValues = ''
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author", author=user.email())
    for gsModel in gasticsModel:
        if (gsModel.AverageGasCost <> 0):
            chartValues += str('%.1f'%(((gsModel.AverageGasCost - 5) * 100) / 8)) + ','
    if chartValues <> '':
        return chartValues.rstrip(',')
    else:
        return ''
    
def GetGasCount(user):
    Y = '|'
    i = 0
    gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE Email = :author", author=user.email())
    for gsModel in gasticsModel:
        if (gsModel.AverageGasCost <> 0):
            Y += str(i) + '|'
        i+=1
    return Y
        
def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()
